package com.meiwenhui.sishuwujing;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.meiwenhui.sishuwujing.adapter.ChapterAdapter;
import com.meiwenhui.sishuwujing.entities.Chapter;
import com.meiwenhui.sishuwujing.util.HttpUtil;
import com.orm.androrm.Filter;

public class ChapterActivity extends BaseActivity implements OnScrollListener {

	private String TAG = "ChapterActivity";

	private LinearLayout mLoadLayout;
	private final LayoutParams mProgressBarLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);
	private final LayoutParams mTipContentLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	private TextView mBookName;
	private TextView mBookAuthor;
	private ListView mChapters;

	private ChapterAdapter chapterAdapter;

	private Integer bookId;
	private int offset = 0;
	private int limit = 60;
	private int mLastItem = 0;
	private int mCount = 0;

	private List<Chapter> chapters = new ArrayList<Chapter>(0);
	private SyncChapter syncChapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chapter);

		mChapters = (ListView) findViewById(R.id.list_chapters);
		chapterAdapter = new ChapterAdapter(ChapterActivity.this, chapters);

		mBookName = (TextView) findViewById(R.id.book_name);
		mBookName.setText("此布局被添加到");

		mBookAuthor = (TextView) findViewById(R.id.book_author);
		mBookAuthor.setText("张三");

		/**
		 * "加载项"布局，此布局被添加到ListView的Footer中。
		 */
		mLoadLayout = new LinearLayout(this);
		mLoadLayout.setMinimumHeight(30);
		mLoadLayout.setGravity(Gravity.CENTER);
		mLoadLayout.setOrientation(LinearLayout.HORIZONTAL);
		/**
		 * 向"加载项"布局中添加一个圆型进度条。
		 */
		ProgressBar mProgressBar = new ProgressBar(this);
		mProgressBar.setPadding(0, 0, 15, 0);
		mLoadLayout.addView(mProgressBar, mProgressBarLayoutParams);
		/**
		 * 向"加载项"布局中添加提示信息。
		 */
		TextView mTipContent = new TextView(this);
		mTipContent.setText("加载中...");
		mLoadLayout.addView(mTipContent, mTipContentLayoutParams);

		mChapters.addFooterView(mLoadLayout);
		mChapters.setAdapter(chapterAdapter);
		mChapters.setOnScrollListener(this);

		bookId = getIntent().getIntExtra("bookId", 18);
		Log.i("bookId", bookId + "");

		syncChapter = new SyncChapter();
		syncChapter.execute(new Integer[] { bookId, offset, limit });

		mChapters.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Chapter chapter = (Chapter) view.getTag();
				Intent intent = new Intent(ChapterActivity.this, DetailActivity.class);
				intent.putExtra("chapterId", chapter.getChapterId());
				startActivity(intent);
			}

		});
	}

	@Override
	public void onScroll(AbsListView view, int mFirstVisibleItem, int mVisibleItemCount, int mTotalItemCount) {
		mLastItem = mFirstVisibleItem + mVisibleItemCount - 1;
		if (chapterAdapter.getCount() > mCount) {
			mChapters.removeFooterView(mLoadLayout);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int mScrollState) {
		if (mLastItem == chapterAdapter.getCount() && mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			if (chapterAdapter.getCount() <= mCount) {
				offset = offset + limit;
				syncChapter = new SyncChapter();
				syncChapter.execute(new Integer[] { bookId, offset, limit });
			}
		}
	}

	private class SyncChapter extends AsyncTask<Integer, Integer, List<Chapter>> {

		@Override
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute() called");
		}

		@Override
		protected List<Chapter> doInBackground(Integer... params) {
			for (Integer integers : params) {
				Log.i("params", integers.toString());
			}
			Filter filter = new Filter();
			filter.is("bookId", params[0]);
			List<Chapter> _chapters = Chapter.objects(ChapterActivity.this, Chapter.class).filter(filter).limit(params[1], params[2])
					.toList();
			Log.i("chapters size", _chapters.size() + "");
			if (_chapters == null || _chapters.size() == 0) {
				try {
					if (mCount != 0) {
						String count = HttpUtil.get(String.format(HttpUtil.GET_CHAPTER_URL, new Object[] { params[0] }));
						JSONArray countja = new JSONArray(count);
						if (countja.length() == 1) {
							mCount = Integer.parseInt(new JSONObject(countja.get(0).toString()).get("count").toString());
							Log.i("mCount", mCount + "");
						}
					}
					String url = String.format(HttpUtil.GET_CHAPTER_URL, (Object[]) params);
					String str = HttpUtil.get(url);
					JSONArray jsonArray = null;
					jsonArray = new JSONArray(str);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
						Chapter chapter = new Chapter();
						chapter.setChapterId(jsonObject.getInt("id"));
						chapter.setName(jsonObject.getString("name"));
						chapter.setBook(jsonObject.getString("book"));
						chapter.setAuthor(jsonObject.getString("author"));
						chapter.setAuthorId(jsonObject.getInt("authorId"));
						chapter.setBookId(bookId.intValue());
						chapter.save(ChapterActivity.this);
						_chapters.add(chapter);
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return _chapters;
		}

		// onProgressUpdate方法用于更新进度信息
		@Override
		protected void onProgressUpdate(Integer... progresses) {
			Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
		}

		// onPostExecute方法用于在执行完后台任务后更新UI,显示结果
		@Override
		protected void onPostExecute(List<Chapter> _chapters) {
			Log.i(TAG, "onPostExecute(Result result) called");
			chapters.addAll(_chapters);
			chapterAdapter.notifyDataSetChanged();
			if (chapterAdapter.getCount() > mCount) {
				mChapters.removeFooterView(mLoadLayout);
			}
		}

		// onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			Log.i(TAG, "onCancelled() called");
		}

	}

}
